#include "common_init.h"

/* board include*/
#include "board_includes.h"
#include "common_includes.h"

/* private functions -------------------------------------------------------- */

#if UCFG_I2C0_ENABLE
static void i2c0_init(void)
{
	eBspGpioConfig(UCFG_I2C0_CLK_PORT, E_BSP_GPIO_OUTPUT, E_BSP_GPIO_NOPULL);
	eBspGpioConfig(UCFG_I2C0_DAT_PORT, E_BSP_GPIO_OUTPUT, E_BSP_GPIO_NOPULL);
}
static void i2c0_scl_set(uint8_t val)
{
	eBspGpioWritePin(UCFG_I2C0_CLK_PORT, val);
}

static void i2c0_sda_set(uint8_t val)
{

	eBspGpioWritePin(UCFG_I2C0_DAT_PORT, val);
}

static void i2c0_sda_dir(uint8_t input)
{
	if (input)
	{
		eBspGpioConfig(UCFG_I2C0_DAT_PORT, E_BSP_GPIO_INPUT, E_BSP_GPIO_NOPULL);
	}
	else
	{
		eBspGpioConfig(UCFG_I2C0_DAT_PORT, E_BSP_GPIO_OUTPUT, E_BSP_GPIO_NOPULL);
	}
}

static uint8_t i2c0_sda_read(void)
{
    return !!eBspGpioReadPin(UCFG_I2C0_DAT_PORT);
}

static void i2c0_delay_us(uint16_t us)
{
    udelay(us);
}

static const i2c_drv_info_t i2c0_cfg =
{
    .mode = I2C_MODE_SW,
    .cfg.sw = {
    	.gpio_init = i2c0_init,
        .scl_set = i2c0_scl_set,
        .sda_set = i2c0_sda_set,
        .sda_dir = i2c0_sda_dir,
        .sda_read = i2c0_sda_read,
        .delay_us = i2c0_delay_us,
        .clock_delay = UCFG_I2C0_DELAY_CNT  // 5us时钟周期
    }
};
#endif

#if UCFG_SPI0_ENABLE
static void spi0_hw_init(void)
{
	spi_open(SPI1);
}
spi_status_e spi0_hw_transfer(const uint8_t *tx_data, uint16_t tx_len,
					   uint8_t *rx_data, uint16_t rx_len)
{
    spi_status_e ret = SPI_OK;

    if (tx_data)
	{
        // 只写操作
		spi_dma_send(SPI1, tx_data, tx_len);
    }

    if (rx_data)
	{
        // 只读操作
		spi_dma_recv(SPI1, rx_data, rx_len);
    }

	return ret;
}

void spi0_cs_control(uint8_t cs_pin, uint8_t status)
{

}

static const spi_drv_info_t spi0_cfg =
{
    .mode = SPI_MODE_HW,
    .cfg.hw.ops = {
		.init = spi0_hw_init,
		.cs_set = spi0_cs_control,
		.transfer = spi0_hw_transfer,
    }
};
#endif
/* public functions -------------------------------------------------------- */
void common_board_init(void)
{
/*-------- System Init-----------*/
	//common_monitor_init();

	common_audio_init();

/*-------- Bsp Init-----------*/
#if UCFG_I2C0_ENABLE
	ej_bsp_i2c_register_bus(UCFG_I2C0_NAME, &i2c0_cfg);
	ej_bsp_i2c_init_bus(UCFG_I2C0_NAME);
#endif

#if UCFG_SPI0_ENABLE
	ej_bsp_spi_register_bus(UCFG_SPI0_NAME, &spi0_cfg);
	ej_bsp_spi_init_bus(UCFG_SPI0_NAME);
#endif

	ej_bsp_adc_init();

}
